{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 此部分内容运行失败，未找到解决办法，待日后再说"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "WARNING:tensorflow:From <ipython-input-1-524b0673a40d>:5: read_data_sets (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use alternatives such as official/mnist/dataset.py from tensorflow/models.\n",
      "WARNING:tensorflow:From D:\\SoftWare\\Anaconda3\\envs\\pyDL\\lib\\site-packages\\tensorflow\\contrib\\learn\\python\\learn\\datasets\\mnist.py:260: maybe_download (from tensorflow.contrib.learn.python.learn.datasets.base) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please write your own downloading logic.\n",
      "WARNING:tensorflow:From D:\\SoftWare\\Anaconda3\\envs\\pyDL\\lib\\site-packages\\tensorflow\\contrib\\learn\\python\\learn\\datasets\\mnist.py:262: extract_images (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use tf.data to implement this functionality.\n",
      "Extracting MNIST_data\\train-images-idx3-ubyte.gz\n",
      "WARNING:tensorflow:From D:\\SoftWare\\Anaconda3\\envs\\pyDL\\lib\\site-packages\\tensorflow\\contrib\\learn\\python\\learn\\datasets\\mnist.py:267: extract_labels (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use tf.data to implement this functionality.\n",
      "Extracting MNIST_data\\train-labels-idx1-ubyte.gz\n",
      "WARNING:tensorflow:From D:\\SoftWare\\Anaconda3\\envs\\pyDL\\lib\\site-packages\\tensorflow\\contrib\\learn\\python\\learn\\datasets\\mnist.py:110: dense_to_one_hot (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use tf.one_hot on tensors.\n",
      "Extracting MNIST_data\\t10k-images-idx3-ubyte.gz\n",
      "Extracting MNIST_data\\t10k-labels-idx1-ubyte.gz\n",
      "WARNING:tensorflow:From D:\\SoftWare\\Anaconda3\\envs\\pyDL\\lib\\site-packages\\tensorflow\\contrib\\learn\\python\\learn\\datasets\\mnist.py:290: DataSet.__init__ (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use alternatives such as official/mnist/dataset.py from tensorflow/models.\n"
     ]
    }
   ],
   "source": [
    "import tensorflow as tf\n",
    "from tensorflow.examples.tutorials.mnist import input_data\n",
    "from tensorflow.contrib.tensorboard.plugins import projector\n",
    "# 载入数据\n",
    "mnist = input_data.read_data_sets('MNIST_data', one_hot=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# 运行次数\n",
    "max_steps = 1001\n",
    "# 图片数量\n",
    "image_num = 3000\n",
    "# 文件路径，\n",
    "DIR = 'E:\\\\ML\\\\DeepL\\\\TensorFLow-Learning\\\\'\n",
    "\n",
    "# 定义会话\n",
    "sess = tf.Session()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "WARNING:tensorflow:From <ipython-input-3-803676636cc3>:39: softmax_cross_entropy_with_logits (from tensorflow.python.ops.nn_ops) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "\n",
      "Future major versions of TensorFlow will allow gradients to flow\n",
      "into the labels input on backprop by default.\n",
      "\n",
      "See @{tf.nn.softmax_cross_entropy_with_logits_v2}.\n",
      "\n"
     ]
    }
   ],
   "source": [
    "# 载入图片，把一定数量的测试图片载入内存\n",
    "embedding = tf.Variable(tf.stack(mnist.test.images[:image_num]), trainable=False, name='embedding')\n",
    "\n",
    "#参数概要\n",
    "def variable_summaries(var):\n",
    "    with tf.name_scope('summaries'):\n",
    "        mean = tf.reduce_mean(var)\n",
    "        tf.summary.scalar('mean',mean)\n",
    "        with tf.name_scope('stddev'):\n",
    "            stddev = tf.sqrt(tf.reduce_mean(tf.square(var-mean)))\n",
    "        tf.summary.scalar('stddev',stddev)\n",
    "        tf.summary.scalar('max',tf.reduce_max(var))\n",
    "        tf.summary.scalar('min',tf.reduce_min(var))\n",
    "        tf.summary.histogram('histogram',var)\n",
    "        \n",
    "# 命名空间\n",
    "with tf.name_scope('Input'):\n",
    "    x = tf.placeholder(tf.float32,[None,784],name='x-input')\n",
    "    y = tf.placeholder(tf.float32,[None,10],name='y-input')\n",
    "    \n",
    "# 显示图片\n",
    "with tf.name_scope('input_reshape'):\n",
    "    image_shaped_input = tf.reshape(x,[-1,28,28,1])\n",
    "    tf.summary.image('input', image_shaped_input,10) # 放进去10张图片\n",
    "\n",
    "with tf.name_scope('layer'):\n",
    "    with tf.name_scope('weights'):\n",
    "        W = tf.Variable(tf.zeros([784,10]),name='W')\n",
    "        variable_summaries(W)\n",
    "    with tf.name_scope('biases'):\n",
    "        b = tf.Variable(tf.zeros([10]),name='b')\n",
    "        variable_summaries(b)\n",
    "    with tf.name_scope('wx_plus_b'):\n",
    "        wx_plus_b = tf.matmul(x,W) + b\n",
    "    with tf.name_scope('softmax'):\n",
    "        prediction = tf.nn.softmax(wx_plus_b)\n",
    "        \n",
    "with tf.name_scope('loss'):\n",
    "    loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y,logits=prediction))\n",
    "    tf.summary.scalar('loss',loss)\n",
    "\n",
    "with tf.name_scope('train'):\n",
    "    train_step = tf.train.GradientDescentOptimizer(0.2).minimize(loss)\n",
    "    \n",
    "sess.run(tf.global_variables_initializer())\n",
    "\n",
    "with tf.name_scope('accuracy'):\n",
    "    with tf.name_scope('correct_prediction'):\n",
    "        correct_prediction = tf.equal(tf.argmax(y,1),tf.argmax(prediction,1))\n",
    "    with tf.name_scope('accuracy'):\n",
    "        accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))\n",
    "        tf.summary.scalar('accuracy',accuracy)\n",
    "        \n",
    "# 产生的metadata文件\n",
    "if tf.gfile.Exists(DIR + 'projector/projector/metadata.tsv'):\n",
    "    tf.gfile.DeleteRecursively(DIR + 'projector/projector/metadata.tsv') #如果该文件存在，先删除\n",
    "with open(DIR + 'projector/projector/metadata.tsv','w') as f:\n",
    "    labels = sess.run(tf.argmax(mnist.test.labels[:],1))  # 拿到测试集所有标签，写入一部分到文件中去 \n",
    "    for i in range(image_num):\n",
    "        f.write(str(labels[i]) + '\\n')\n",
    "        \n",
    "# 合并所有summary\n",
    "merged = tf.summary.merge_all()\n",
    "\n",
    "# 定义一个writer，写入图\n",
    "projector_writer = tf.summary.FileWriter(DIR + 'projector/projector',sess.graph)\n",
    "#用来保存网络模型\n",
    "saver = tf.train.Saver()\n",
    "# 定义配置文件\n",
    "config = projector.ProjectorConfig()\n",
    "embed = config.embeddings.add()\n",
    "embed.tensor_name = embedding.name\n",
    "embed.metadata_path = DIR + 'projector/projector/metadata.tsv'\n",
    "embed.sprite.image_path = DIR + 'projector/data/mnist_10k_sprite.png'\n",
    "# 切分图片\n",
    "embed.sprite.single_image_dim.extend([28,28])\n",
    "projector.visualize_embeddings(projector_writer, config)\n",
    "\n",
    "for i in range(max_steps):\n",
    "    batch_xs,batch_ys = mnist.train.next_batch(100)\n",
    "    run_options = tf.RunOptions(trace_level=tf.RunOptions.FULL_TRACE)\n",
    "    run_metadata = tf.RunMetadata()\n",
    "    summary,_  = sess.run([merged, train_step], feed_dict={x:batch_xs,y:batch_ys}, options=run_options, run_metadata=run_metadata)\n",
    "    projector_writer.add_run_metadata(run_metadata,'step%03d' % i)\n",
    "    projector_writer.add_summary(summary, i)\n",
    "    \n",
    "    if i%100 == 0:\n",
    "        acc = sess.run(accuracy, feed_dict={x:mnist.test.images, y:mnist.test.labels})\n",
    "        print(\"Iter \" + str(i) + \", Testing Accuracy= \" + str(acc))\n",
    "        \n",
    "saver.save(sess, DIR + 'projector/projector/a_model.ckpt', global_step=max_steps)\n",
    "projector_writer.close()\n",
    "sess.close()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
